package monitori_di_hoare;

public class MailBox<T> extends BufferLimitato<T> {
	protected Monitor m = new Monitor();
	protected Condition nonEmpty = m.newCondition();
	protected Condition nonFull = m.newCondition();

	public MailBox(int n) {
		super(n);
	}

	public T get() {
		m.Enter();
		try {
			if (count == 0)
				nonEmpty.Wait();
			T ans = buffer[out];
			out = (out + 1) % n;
			count--;
			nonFull.Signal();
			return ans;
		} finally {
			m.Exit();
		}
	}// get

	public void put(T value) {
		m.Enter();
		try {
			if (count == n)
				nonFull.Wait();
			buffer[in] = value;
			in = (in + 1) % n;
			count++;
			nonEmpty.Signal();
		} finally {
			m.Exit();
		}
	}// put
}
